// --- Copyright (c) notice NevoWeb ---
//  Copyright (c) 2014 SARL NevoWeb.  www.nevoweb.com.
// Author: D.C.Lee
// ------------------------------------------------------------------------
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// ------------------------------------------------------------------------
// This copyright notice may NOT be removed, obscured or modified without written consent from the author.
// --- End copyright notice --- 

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Entities.Portals;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

using Nevoweb.DNN.NBrightBuy.Base;
using Nevoweb.DNN.NBrightBuy.Components;
using DataProvider = DotNetNuke.Data.DataProvider;

namespace Nevoweb.DNN.NBrightBuyQuickCategory
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The ViewNBrightGen class displays the content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class QuickCategory : NBrightBuyAdminBase
    {


        #region Event Handlers

        private String _ctrlkey = "";
        private NBrightBuyController _modCtrl;

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                _modCtrl = new NBrightBuyController();

                _ctrlkey = (String)HttpContext.Current.Session["nbrightbackofficectrl"];

                #region "load templates"

                var t2 = "QuickCategorybody.html";
                // Get Display Header
                var rpDataHTempl = GetTemplateData(t2);
                rpData.ItemTemplate = NBrightBuyUtils.GetGenXmlTemplate(rpDataHTempl, StoreSettings.Current.Settings(), PortalSettings.HomeDirectory);

                #endregion


            }
            catch (Exception exc)
            {
                //display the error on the template (don;t want to log it here, prefer to deal with errors directly.)
                var l = new Literal();
                l.Text = exc.ToString();
                Controls.Add(l);
            }

        }

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                base.OnLoad(e);

                if (Page.IsPostBack == false)
                {
                    PageLoad();
                }
            }
            catch (Exception exc) //Module failed to load
            {
                //display the error on the template (don;t want to log it here, prefer to deal with errors directly.)
                var l = new Literal();
                l.Text = exc.ToString();
                Controls.Add(l);
            }
        }

        private void PageLoad()
        {
            if (UserId > 0) // only logged in users can see data on this module.
            {
                // display header
                base.DoDetail(rpData, new NBrightInfo());
            }
        }

        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();
            var param = new string[3];
            param[0] = "ctrl=" + _ctrlkey;
            switch (e.CommandName.ToLower())
            {
                case "save":
                    Update();
                    Response.Redirect(Globals.NavigateURL(TabId, "", param), true);
                    break;
                case "undo":
                    Undo();
                    Response.Redirect(Globals.NavigateURL(TabId, "", param), true);
                    break;
                case "keep":
                    Keep();
                    Response.Redirect(Globals.NavigateURL(TabId, "", param), true);
                    break;
                case "cancel":
                    Response.Redirect(Globals.NavigateURL(TabId, "", param), true);
                    break;
            }

        }

        #endregion

        private String GetTemplateData(String templatename)
        {
            var controlMapPath = HttpContext.Current.Server.MapPath("/DesktopModules/NBright/NBrightBuyQuickCategory");
            var templCtrl = new NBrightCore.TemplateEngine.TemplateGetter(PortalSettings.Current.HomeDirectoryMapPath, controlMapPath, "Themes\\config", "");
            var templ = templCtrl.GetTemplateData(templatename, Utils.GetCurrentCulture());
            templ = Utils.ReplaceSettingTokens(templ, StoreSettings.Current.Settings());
            templ = Utils.ReplaceUrlTokens(templ);
            return templ;
        }

        private void Update()
        {
            try
            {

            var strData = GenXmlFunctions.GetField(rpData, "datainput");
            var ary = strData.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            var prevparentids = new List<int>();
            foreach (var r in ary)
            {
                if (r != "")
                {
                    var catary = r.Split('>');
                    var lp = 1;
                    var parentids = new List<int>();
                    foreach (var c in catary)
                    {
                        if (catary.Count() == lp)
                        {
                            // add last node in breadcrumb, update as new category 
                            var categoryData = new CategoryData(-1, EditLanguage);
                            categoryData.DataLangRecord.SetXmlProperty("genxml/textbox/txtcategoryname", c);
                            categoryData.ParentItemId = 0;
                            categoryData.GroupType = "cat";
                            if (parentids.Any()) categoryData.ParentItemId = parentids.Last(); 
                            categoryData.DataRecord.SetXmlProperty("genxml/createdby","quickcategory");
                            categoryData.Save();
                            parentids.Add(categoryData.CategoryId);
                            prevparentids = parentids;
                        }
                        else
                        {
                            if (c == "")
                            {
                                 // assume if no parent specified then the previous created parent category structure is used.
                                if (prevparentids.Count() >= parentids.Count() && prevparentids.Any())
                                    parentids.Add(prevparentids[parentids.Count]);
                                else
                                {
                                    NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.fail, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
                                    return;
                                }
                            }
                            else
                            {
                                var strFilter = "";
                                if (parentids.Any())
                                    strFilter = " and NB1.ParentItemId = " + parentids.Last().ToString("") + " and [XMLData].value('(genxml/lang/genxml/textbox/txtcategoryname)[1]','nvarchar(max)') = '" + c + "' ";
                                else
                                    strFilter = " and NB1.ParentItemId = 0 and [XMLData].value('(genxml/lang/genxml/textbox/txtcategoryname)[1]','nvarchar(max)') = '" + c + "' ";
                                var l = ModCtrl.GetDataList(PortalId, -1, "CATEGORY", "CATEGORYLANG", EditLanguage, strFilter, "");
                                if (l.Any())
                                {
                                    parentids.Add(l.Last().ItemID);
                                }                                
                            }
                        }
                        lp += 1;
                    }

                }
            }
            NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.ok, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }
            catch (Exception)
            {
                NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.fail, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }

        }


        private void Undo()
        {
            try
            {
                var strFilter = " and [XMLData].value('(genxml/createdby)[1]','nvarchar(max)') = 'quickcategory' ";
                var l = ModCtrl.GetDataList(PortalId, -1, "CATEGORY", "CATEGORYLANG", EditLanguage, strFilter, "");
                foreach (var c in l)
                {
                    ModCtrl.Delete(c.ItemID);
                    c.SetXmlProperty("genxml/createdby", "");
                }
                NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.ok, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }
            catch (Exception)
            {
                NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.fail, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }

        }


        private void Keep()
        {
            try
            {
                var strFilter = " and [XMLData].value('(genxml/createdby)[1]','nvarchar(max)') = 'quickcategory' ";
                var l = ModCtrl.GetDataList(PortalId, -1, "CATEGORY", "CATEGORYLANG", EditLanguage, strFilter, "");
                foreach (var c in l)
                {
                    var catData = new CategoryData(c.ItemID, EditLanguage);
                    catData.DataRecord.RemoveXmlNode("genxml/createdby");
                    catData.IsHidden = false;
                    catData.Save();
                }
                NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.ok, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }
            catch (Exception)
            {
                NBrightBuyUtils.SetNotfiyMessage(ModuleId, "quickcategory", NotifyCode.fail, "/DesktopModules/NBright/NBrightBuyQuickCategory/App_LocalResources/QuickCategory.ascx.resx");
            }

        }


    }

}
